package com.cqvip.innocence.project.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.cqvip.innocence.common.util.redis.RedisService;
import com.cqvip.innocence.framework.config.capcha.CapchaConfig;
import com.cqvip.innocence.project.model.dto.JsonResult;
import com.cqvip.innocence.project.service.CapchaCodeGen;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.cqvip.innocence.framework.config.capcha.CapchaConfig.CAPCHA_REDIS_EXPIRATION;
import static com.cqvip.innocence.framework.config.capcha.CapchaConfig.CAPCHA_REDIS_KEY;


/**
 * @ClassName CapchaCodeGenImpl
 * @Description 验证码实现类
 * @Author Innocence
 * @Date 2020/7/28
 * @Version 1.0
 */
@Service
public class CapchaCodeGenImpl implements CapchaCodeGen {

    @Autowired
    private CapchaConfig capchaConfig;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisService redisService;

    @Override
    public JsonResult createCapcha() {
        JsonResult json = JsonResult.Get();
        boolean captchaOnOff = capchaConfig.getEnabled();
        json.put("captchaOnOff", captchaOnOff);
        if (!captchaOnOff) {
            return json;
        }

        // 保存验证码信息
        String uuid = UUID.fastUUID().toString();
        String verifyKey = CAPCHA_REDIS_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        String captchaType = capchaConfig.getType();
        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisService.set(verifyKey, code, CAPCHA_REDIS_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return JsonResult.Get(false, e.getMessage());
        }

        json.put("uuid", uuid);
        json.put("img", Base64.encode(os.toByteArray()));
        return json;
    }

    @Override
    public JsonResult checkCapcha(String code, String uuid) {
        JsonResult jsonResult = JsonResult.Get();
        if (StrUtil.isBlank(code)) {
            return jsonResult.set(false, "验证码不能为空！");
        }
        String verifyKey = CAPCHA_REDIS_KEY + uuid;
        Object o = redisService.get(verifyKey);
        if (StrUtil.isBlank(uuid) || null == o) {
            return jsonResult.set(false, "验证码已失效");
        }
        String captcha = (String) o;
        redisService.del(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            return jsonResult.set(false, "验证码错误");
        }
        return null;
    }
}
